package com.freight.order.serviceimpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freight.base.utils.AreaAddressUtil;
import com.freight.base.utils.AreaDtoUtil;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import com.freight.core.service.SettingService;
import com.freight.order.dto.DriverGoodsDto;
import com.freight.order.mapper.OrderMainMapper;
import com.freight.order.service.DiverHistoricalRecordsService;
import com.freight.order.vo.DriverGoodsVo;
import com.freight.user.service.ICompanyVoService;
import com.freight.user.util.UserVoUtils;
import com.freight.user.vo.AppointCompanyInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

@Slf4j
@Service
@Transactional
public class DiverHistoricalRecordsServiceImpl implements DiverHistoricalRecordsService {

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private AreaAddressUtil areaAddressUtil;


    @Autowired
    private ICompanyVoService iCompanyVoService;



    @Autowired
    private SettingService settingService;

    @Autowired
    SecurityUtil securityUtil;


    @Override
    public Page<DriverGoodsVo> getHistoricalRecords(Page<DriverGoodsVo> page, DriverGoodsDto driverGoodsDto) {

        User u = securityUtil.getCurrUser();
        if (u == null) {
            throw new FreightException("登入失效或尚未登入，请先登入");
        }

        driverGoodsDto = AreaDtoUtil.getAreaDtoSeatch(driverGoodsDto);

        Page<DriverGoodsVo> res = orderMainMapper.getHistoricalRecords(page, driverGoodsDto, u.getId());
        List<DriverGoodsVo> records = res.getRecords();
        areaAddressUtil.fillAreaAddress(records);
        HashSet<Long> companyUserIds = new HashSet<>();
        for (DriverGoodsVo record : records) {
            companyUserIds.add(record.getCompanyUserId());
        }
        Long[] comUserIds = companyUserIds.stream().toArray(Long[]::new);
        List<Long> comUserIdList = Arrays.asList(comUserIds);

        // 获取货主信息
        List<AppointCompanyInfoVo> aCompanys = iCompanyVoService.getAppointCompanyInfoVoByUserIds(comUserIds);

        HashMap<Long, AppointCompanyInfoVo> aMapCompany = UserVoUtils.listToHashMap(aCompanys);

        for (DriverGoodsVo record : records) {
            AppointCompanyInfoVo company = aMapCompany.get(record.getCompanyUserId());
            record.setCargoOwnerInfoVo(company);
        }
        return res;

    }
}
